package cn.lzm.server.tcp;

import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;

/**
 * @author lzm
 * @Date 2024/11/5
 * @description 测试tcp的半包和粘包 注意看这里构造的消息的第4个字节开始才是消息的长度， 所以VertxTcpServerV4才使用
 * buffer.getInt(4)来获取消息体的长度
 */
public class VertxTcpClientV3 {

    public void start() {
        Vertx vertx = Vertx.vertx();
        vertx.createNetClient().connect(8404, "localhost", result -> {
            if (result.succeeded()) {
                System.out.println("connected to server");
                NetSocket socket = result.result();
                for (int i = 0; i < 1000; i++) {

                    String str = "hello, server! hello, server! hello, server! hello, server!";
                    Buffer buffer = Buffer.buffer();
                    // 前4个字节（0,1,2，3）随意放个0
                    buffer.appendInt(0);
                    // 添加消息的长度
                    buffer.appendInt(str.getBytes().length);
                    buffer.appendBytes(str.getBytes());
                    socket.write(buffer);
                }
                socket.handler(buffer -> {
                    System.out.println("received response from server: " + buffer.toString());
                });
            } else {
                System.err.println("failed to connect to tcp server");
            }
        });
    }

    public static void main(String[] args) {
        new VertxTcpClientV3().start();
    }
}
